<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.gxgyl.com All rights reserved.

// +----------------------------------------------------------------------
// | Author: Liuyu
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\store\model\shiyao;

use app\common\model\shiyao\Project as ProjectModel;
use app\common\service\store\User as UserService;
use think\facade\Db;

/**
 * 申办方模型
 * Class StoreUser
 * @package app\store\model
 */
class Project extends ProjectModel {

	public function getListAll($param = []) {
		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['companyId' => '', 'search' => '', 'logids' => []]);
		$filter = [];
		!empty($params['companyId']) && $query->where('p.company_id', '=', $params['companyId']);
		if (!empty($params['logids'])) {
$query->where('p.project_id', 'in', $params['logids']);
		}

		// 关键词搜索
		!empty($params['search']) && $query->where('p.project_name|c.company_name|p.project_code', 'like', "%{$params['search']}%");
		// 查询列表记录
		$list = $query->alias('p')->with(['pm', 'company'])
			->field('p.*')
			->join('shiyao_company c', 'c.company_id=p.company_id')
			->where($filter)
			->where('p.is_delete', '=', '0')
			->order(['p.project_code' => 'asc', 'create_time' => 'desc'])
			->select()->toArray();

			foreach ($list as $key => $value) {
					$list[$key]['center_num'] = Db::name('shiyao_project_center')
				->where('project_id', $value['project_id'])->where('is_delete', 0)->where('status', 1)->count();
				$list[$key]['pm']=$value['pm']['nick_name'];
				
			}

		return $list;
	}

	/**
	 * 获取项目-总后台
	 * @param array $param
	 * @return \think\Paginator
	 * @throws \think\db\exception\DbException
	 */
	public function getList($param = []) {
		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['companyId' => '', 'search' => '', 'betweenTime' => []]);
		$filter = [];
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}

		$store_user = UserService::getLoginInfo();
		$store_user = $store_user['user'];

		if ($store_user['company_id'] > 0) {
			$query->where('c.company_id', '=', $store_user['company_id']);
		}

		!empty($params['companyId']) && $query->where('p.company_id', '=', $params['companyId']);

		// 关键词搜索
		!empty($params['search']) && $query->where('p.project_name|c.company_name|p.project_code', 'like', "%{$params['search']}%");
		// 查询列表记录
		$list = $query->alias('p')->with(['pm', 'company'])
			->field('p.*')
			->join('shiyao_company c', 'c.company_id=p.company_id')
			->where('p.is_delete', '=', '0')
			->where($filter)
			->order(['p.project_code' => 'asc'])
			->paginate(15)->each(function ($item, $key) {
			$item['center_num'] = Db::name('shiyao_project_center')
				->where('project_id', $item['project_id'])->where('is_delete', 0)->where('status', 1)->count();

		});

		return $list;
	}

	/**
	 * 获取项目-申办方
	 * @param array $param
	 * @return \think\Paginator
	 * @throws \think\db\exception\DbException
	 */
	public function getListCompany($param = []) {
		$store_user = UserService::getLoginInfo();
		$store_user = $store_user['user'];
		// 查询模型
		$query = $this->getNewQuery();
		// 查询参数
		$params = $this->setQueryDefaultValue($param, ['companyId' => '', 'search' => '', 'betweenTime' => []]);

		$filter = [];
		// 起止时间
		if (!empty($params['betweenTime'])) {
			$times = between_time($params['betweenTime']);
			$filter[] = ['p.create_time', '>=', $times['start_time']];
			$filter[] = ['p.create_time', '<', $times['end_time'] + 86400];
		}
		!empty($store_user['company_id']) && $query->where('p.company_id', '=', $store_user['company_id']);

		//根据角色筛选
		$role = Db::name('store_user_role')->where('role_id', 'in', [10006, 10009])
			->where('store_user_id', $store_user['store_user_id'])->find();
		if ($store_user['company_id']) {
			if ($role) {
				//申办方超级管理员

			} else {
				//pm用户id
				$userId = Db::name('user')->where('mobile', $store_user['user_name'])->value('user_id');

				//协助pm
				$pm = Db::name('shiyao_project_pm')->where('pm_id', $userId)->select()->toArray();
				$query->where(function ($query) use ($pm, $userId) {
					//$query->where('p.pm_id', '=', $userId);
					if ($pm) {
						$ids = array_column($pm, 'project_id');
						$query->whereOr('p.project_id', 'in', $ids);
					}

				});

			}

		}

		// 关键词搜索
		!empty($params['search']) && $query->where('p.project_name|c.company_name|p.project_code', 'like', "%{$params['search']}%");
		// 查询列表记录
		$list = $query->alias('p')->with(['pm', 'company'])
			->field('p.*')
			->join('shiyao_company c', 'c.company_id=p.company_id')
			->where('p.is_delete', '=', '0')
			->where($filter)
			->order(['p.create_time' => 'desc'])
			->paginate(15)->each(function ($item, $key) {
			$item['testee_count'] = Db::name('shiyao_project_center_testee')
				->where('project_id', $item['project_id'])->where('is_delete', 0)->count();
			$item['center_count'] = Db::name('shiyao_project_center')
				->where('project_id', $item['project_id'])->where('is_delete', 0)->count();
			return $item;
		});

		return $list;
	}
	/**
	 * 关闭
	 * @param array $goodsIds 商品id集
	 * @param bool $state 为true表示上架
	 * @return bool|false
	 */
	public function setStatus(array $goodsIds, bool $state): bool {

		// 批量更新记录

		return static::updateBase(['is_close' => 1], [['project_id', 'in', $goodsIds]]);
	}
	/**
	 * 新增记录
	 * @param array $data
	 * @return bool
	 */
	public function add(array $data) {
		$store_user = UserService::getLoginInfo();
		$data['project_name'] = $data['project_name'];

		$data['company_id'] = $store_user['user']['company_id'];
		$data['pm_id'] = Db::name('user')->where('mobile', $store_user['user']['user_name'])->value('user_id');
		if (!$data['pm_id']) {
			$this->error = '非申办方人员，不能添加项目';
			return false;
		}

		$data['store_id'] = self::$storeId;

		// 事务处理
		$this->transaction(function () use ($data) {
			// 新增
			$this->save($data);

		});
		return true;
	}

	public function addPm(array $data) {

		// 事务处理
		$this->transaction(function () use ($data) {
			Db::name('shiyao_project_pm')->where('project_id', $this->project_id)->delete();
			foreach ($data['pm_ids'] as $key => $pm) {
				$pm_data['project_id'] = $this->project_id;
				$pm_data['pm_id'] = $pm['value'];
				$pm_data['is_share'] = $data['is_share'];
				$pm_data['create_time'] = time();
				$pm_data['store_id'] = self::$storeId;
				Db::name('shiyao_project_pm')->insert($pm_data);
			}

			$dataUpdate['is_share'] = $data['is_share'];
			$dataUpdate['pm_ids'] = json_encode($data['pm_ids']);
			$dataUpdate['pm_ids_audit'] = json_encode($data['pm_ids_audit']);

			// 更新
			$this->save($dataUpdate);

		});
		return true;
	}

	/**
	 * 更新记录
	 * @param array $data
	 * @return bool
	 */
	public function edit(array $data) {
		$data['project_name'] = $data['project_name'];

		$this->transaction(function () use ($data) {
			// 更新记录
			$this->save($data);

		});
		return true;
	}

	public function audit(array $data) {

		$this->transaction(function () use ($data) {
			// 更新记录
			$this->save($data);

		});
		return true;
	}

	/**
	 * 软删除
	 * @return false|int
	 */
	public function setDelete() {
		$projectId = $this->project_id;
		$centerlog = Db::name('shiyao_project_center')->where('project_id', $projectId)->find();
		if ($centerlog) {

			$this->error = '当前项目有中心记录，不允许删除';
			return false;
		}
		$buzhulog = Db::name('shiyao_project_pay_log')->where('project_id', $projectId)->find();

		if ($buzhulog) {

			$this->error = '当前项目有补助记录，不允许删除';
			return false;
		}

		return $this->save(['is_delete' => 1]);

	}
	public static function detail(int $projectId) {

		$detail = self::get(['project_id' => $projectId]);

		return $detail;
	}

}
